﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using SqlSugar;
using Star.Model;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Star.Common.Seed
{
    public class InitDB
    {
        public IConfiguration _config { get; set; }

        public InitDB(IConfiguration config)
        {
            _config = config;
        }

        public void InitDBBuild(IServiceCollection service) {
            #region SqlSugar


            // 把多个连接对象注入服务，这里必须采用Scope，因为有事务操作
            service.AddScoped<ISqlSugarClient>(o =>
            {
                // 连接字符串
                var listConfig = new List<ConnectionConfig>();
                listConfig.Add(new ConnectionConfig() { ConnectionString = _config.GetConnectionString("SugarConnectString"), DbType = DbType.PostgreSQL, InitKeyType = InitKeyType.Attribute, IsAutoCloseConnection = true }
              );
                return new SqlSugarScope(listConfig);
            });


            service.AddScoped(options =>
            {
                var client = new SqlSugarClient(new List<ConnectionConfig>()
    {
        new ConnectionConfig() { ConnectionString = _config.GetConnectionString("SugarConnectString"), DbType = DbType.PostgreSQL,InitKeyType = InitKeyType.Attribute, IsAutoCloseConnection = true }
    });
                client.Aop.OnLogExecuting = (sql, pars) =>
                {
                    Console.WriteLine(sql + "\r\n" +
                    client.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
                    Console.WriteLine();
                };
                return client;
            });//单例注入SqlSugar
            service.AddScoped<MyContext>();
            service.AddDbContext<StarDbContext>(option =>
            {
                option.UseNpgsql(_config.GetConnectionString("SugarConnectString"));

            });//efcode  用于codefrist
            #endregion
        }
    }
}
